package www.openteam.com.ui.business.other;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;

import com.cundong.recyclerview.EndlessRecyclerOnScrollListener;
import com.cundong.recyclerview.HeaderAndFooterRecyclerViewAdapter;

import java.util.ArrayList;

import www.openteam.com.R;
import www.openteam.com.adapter.other.SomeCustomInfoAdapter;
import www.openteam.com.base.mBaseFragment;
import www.openteam.com.bean.SomeCustomInfo;
import www.openteam.com.contract.business.other.SearchSomeCustomInfoContract;
import www.openteam.com.presenter.business.other.SearchSomeCustomInfoPresenter;
import www.openteam.com.tool.RecyclerViewStateUtils;
import www.openteam.com.tool.ToastUtil;
import www.openteam.com.widget.LoadingFooter;

/**
 * Created by kylin on 2016/11/30.
 */

public class SearchCustomFragment extends mBaseFragment<SearchSomeCustomInfoPresenter>
        implements SearchSomeCustomInfoContract.SearchSomeCustomInfoView {


    private final String TAG = SearchCustomFragment.class.getSimpleName();
    private RecyclerView mRecyclerView;
    private LinearLayoutManager linearLayoutManager;
    private SomeCustomInfoAdapter someCustomInfoAdapter;
    int pageSize= 0;
    int i = 0;
    private Throwable throwable;
    private ArrayList<SomeCustomInfo.DataEntity> someCustomInfo;
    private ArrayList<SomeCustomInfo.DataEntity>   handleSomeCustomInfo;
    String name="";
    private EditText et_search;
    private HeaderAndFooterRecyclerViewAdapter mFooterRecyclerViewAapter;
    private ButtonSelect buttonSelect;
    private ImageView iv_search;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(getLayoutId(), container, false);
        iv_search = (ImageView) view.findViewById(R.id.iv_search);
        et_search = (EditText) view.findViewById(R.id.et_search);

        initRView(view);
        mRecyclerView.addOnScrollListener(mOnScrollListener);
        mPresenter = loadPresenter();
        initCommonData();
        initView();
        initListener();
        initData();

        return view;
    }


    private void initCommonData() {
        if (mPresenter != null)
            mPresenter.attachView(this);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {
        iv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                name = et_search.getText().toString();
                if (someCustomInfoAdapter == null) {
                    someCustomInfo = new ArrayList<SomeCustomInfo.DataEntity>();
                    handleSomeCustomInfo = new ArrayList<SomeCustomInfo.DataEntity>();
                    mPresenter.querySomeCustomInfo(et_search.getText().toString(), pageSize);
                } else {
                    someCustomInfoAdapter.deleteItems(someCustomInfo);
                    mRecyclerView.removeAllViews();
                    someCustomInfo.clear();
                    throwable = null;
                    i = 0;
                    handleSomeCustomInfo.clear();
                    onRefresh();
                }
            }
        });
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_search;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void otherViewClick(View view) {

    }

    @Override
    protected SearchSomeCustomInfoPresenter loadPresenter() {
        return new SearchSomeCustomInfoPresenter();
    }

    public void initRView(View view) {

        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview_search);

        linearLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(linearLayoutManager);

    }

    public EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(mRecyclerView);
            if (state == LoadingFooter.State.Loading) {
                Log.d("@Cundong", "the state is Loading, just wait..");
                i++;
            }
            i++;
            if (throwable == null && (someCustomInfo.size() % 10 == 0)) {

                Log.d(TAG, "onLoadNextPage: jx");
                someCustomInfo = new ArrayList<SomeCustomInfo.DataEntity>();
                handleSomeCustomInfo = new ArrayList<SomeCustomInfo.DataEntity>();
                mPresenter.querySomeCustomInfo(et_search.getText().toString(),i);
                RecyclerViewStateUtils.
                        setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.Loading, null);
            } else if (throwable == null && (someCustomInfo.size() % 10 != 0)) {
                //the end
                Log.d(TAG, "onLoadNextPage:  !-9 ");
                mPresenter.querySomeCustomInfo(et_search.getText().toString(),i);
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                throwable = null;
            } else if (throwable != null) {
                //the end
                i = 0;
                if (throwable.toString().equals("com.google.gson.JsonSyntaxException:java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 42 path $.data")) {
                    Log.d(TAG, "onLoadNextPage:  bunull ");
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                    throwable = null;
                }
            }

        }
    };

    private void setSomeCustomInfosAdapter() {
        if (someCustomInfoAdapter == null) {
            someCustomInfoAdapter = new SomeCustomInfoAdapter(getActivity());
            someCustomInfoAdapter.addItems(someCustomInfo);
            someCustomInfoAdapter.addContext(getActivity());
            someCustomInfoAdapter.scButtonSetOnclick(new SomeCustomInfoAdapter.SCButtonTouchEvent() {
                @Override
                public void doubleClickSelect(SomeCustomInfo.DataEntity someCustomInfo) {
                    buttonSelect.buttonOnclickSelect(someCustomInfo);
                }
            });
            mFooterRecyclerViewAapter = new HeaderAndFooterRecyclerViewAdapter(someCustomInfoAdapter);
            mRecyclerView.setAdapter(mFooterRecyclerViewAapter);
            RecyclerViewStateUtils.setFooterViewState(this.mRecyclerView, LoadingFooter.State.Normal);
        } else {
            mFooterRecyclerViewAapter.notifyDataSetChanged();
            someCustomInfoAdapter.addItems(someCustomInfo);
            someCustomInfoAdapter.addContext(getActivity());
            someCustomInfoAdapter.scButtonSetOnclick(new SomeCustomInfoAdapter.SCButtonTouchEvent() {
                @Override
                public void doubleClickSelect(SomeCustomInfo.DataEntity SomeCustomInfo) {
                    buttonSelect.buttonOnclickSelect(SomeCustomInfo);
                }
            });
            RecyclerViewStateUtils.setFooterViewState(this.mRecyclerView, LoadingFooter.State.Normal);
        }
    }

    @Override
    public void loadSCIData(SomeCustomInfo SomeCustomInfo) {
        for (SomeCustomInfo.DataEntity dev : SomeCustomInfo.getData()) {
            this.someCustomInfo.add(dev);
            handleSomeCustomInfo.add(dev);
        }
        setSomeCustomInfosAdapter();
    }

    @Override
    public void hideSCIData(Throwable throwable) {
        this.throwable = throwable;
        if (throwable.toString().equals("com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 42 path $.data")
                || throwable.toString().equals("retrofit2.adapter.rxjava.HttpException: HTTP 500 Internal Server Error")) {
            Log.d(TAG, "hideProgress:  bunull ");
            RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
            ToastUtil.showToast(getActivity(), "暂无匹配数据");
        } else {
            Log.d(TAG, "hideProgress:  esle ");
            RecyclerViewStateUtils.setFooterViewState(getActivity(), this.mRecyclerView, REQUEST_COUNT, LoadingFooter.State.NetWorkError, this.mFooterClick);
            ToastUtil.showToast(getActivity(), "网络连接有误");
        }
    }
    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.Loading, null);
            mPresenter.querySomeCustomInfo(name,  i);
        }
    };

    public interface  ButtonSelect{

        void buttonOnclickSelect(SomeCustomInfo.DataEntity SomeCustomInfo);

    }


    public void buttonSetOnclick(ButtonSelect buttonSelect) {
        this.buttonSelect = buttonSelect;
    }

    public void onRefresh() {
        if ((mRecyclerView.getChildCount() > 0) && (!et_search.getText().toString().isEmpty()) ){
            Log.d(TAG, "onRefresh: " + mRecyclerView.getChildCount());
            mRecyclerView.removeAllViews();
            someCustomInfo.clear();
            someCustomInfoAdapter = null;
            handleSomeCustomInfo.clear();
            mFooterRecyclerViewAapter = null;
            mPresenter.querySomeCustomInfo(et_search.getText().toString(), 0);
            throwable = null;
            i = 0;
        } else if ((mRecyclerView.getChildCount() <= 0) && (!et_search.getText().toString().isEmpty() )) {
            mRecyclerView.removeAllViews();
            someCustomInfoAdapter = null;
            someCustomInfo.clear();
            handleSomeCustomInfo.clear();
            i=0;
            mPresenter.querySomeCustomInfo(et_search.getText().toString(), 0);
        } else if ((mRecyclerView.getChildCount() >= 0) && (mRecyclerView != null)) {

            mRecyclerView.removeAllViews();
            someCustomInfoAdapter = null;
            someCustomInfo.clear();
            handleSomeCustomInfo.clear();
            i=0;
            mPresenter.querySomeCustomInfo(  et_search.getText().toString(), 0);
        }
    }

}
